from datetime import datetime
from celery import shared_task

import os
from books.models import Book
@shared_task
def generate_monthly_report(month=None, year=None):
    if month is None or year is None:
        now = datetime.now()
        month = now.month
        year = now.year
    # Query database for books published in the specified month and year
    start_date = datetime(year, month, 1)
    end_date = start_date.replace(day=1, month=month+1) - datetime.timedelta(days=1)
    books_published = Book.objects.filter(publication_date__range=[start_date, end_date])

    # Calculate statistics
    authors_count = books_published.values('author').distinct().count()
    books_count = books_published.count()

    # Prepare report text
    report_text = (
        f"Monthly Report for {month}/{year}\n"
        f"Total Authors: {authors_count}\n"
        f"Total Books: {books_count}\n"
    )

    # Save report to a file
    report_dir = '../celery_task/reports'
    report_filename = f'monthly_report_{year}_{month}.txt'
    report_path = os.path.join(report_dir, report_filename)
    with open(report_path, 'w') as file:
        file.write(report_text)
    return {'filename': report_filename}